<template>
    <div>
        <el-form>
            <!-- <el-row>
                <el-col :span="12">
                    <el-form-item label="经度" prop="longitude">
                        <el-input style="width: 200px" disabled v-model="form.longitude"></el-input>
                    </el-form-item></el-col>
                <el-col :span="12">
                    <el-form-item label="纬度" prop="latitude">
                        <el-input style="width: 200px" disabled v-model="form.latitude"></el-input>
                    </el-form-item></el-col>
            </el-row> -->
            <el-form-item>


                <div class="map-box">
                    <div class="map" ref="map" style="height: 300px" />
                    <div class="map-search">
                        <el-input v-model="searchValue" placeholder="请输入要检索的位置信息" />
                        <el-button @click="searchAddress(searchValue)" type="primary">搜索</el-button>
                    </div>
                </div>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
export default {
    data() {
        return {
            searchValue: '', //地图搜索
            form: {
                longitude: '',
                latitude: '',
            }
        }
    },
    created() {
        if (this.script) return;
        this.script = document.createElement('script');
        this.script.type = 'text/javascript';
        this.script.src = `//map.qq.com/api/gljs?v=1.exp&libraries=service&key=IN4BZ-4QQEU-OR7VQ-BPMCY-EAC26-CHFTJ`;
        document.head.appendChild(this.script);
        this.script.onload = () => {
            window.initMap = this.initMap;
            this.$nextTick(() => {
                this.initMap();
            });
        };
    },
    methods: {
        // 地图
        initMap() {
            // 搜索类
            this.searchEr = new window.TMap.service.Search({ pageSize: 10 });
            // 地图主类
            this.map = new window.TMap.Map(this.$refs.map, {
                backgroundColor: '#f7f7f7',
                mapStyleId: 'style1',
                zoom: 12,
                mapTypeControlOptions: {
                    mapTypeIds: [],
                },
                draggableCursor: 'crosshair',
                center: new window.TMap.LatLng(32.034221, 118.775489),
            });
            // 图层类
            this.markerLayer = new window.TMap.MultiMarker({
                map: this.map,
                geometries: [],
            });
            // 地址逆解析
            this.geocoder = new window.TMap.service.Geocoder();
            const setMarker = () => {
                const latlng = new window.TMap.LatLng(this.form.latitude, this.form.longitude);
                this.markerLayer.setGeometries([]);
                let geometries = this.markerLayer.getGeometries();
                geometries.push({
                    id: '-1',
                    position: latlng,
                });
                this.markerLayer.updateGeometries(geometries);
            };
            this.map.on('click', (e) => {
                this.searchValue = ""
                this.form.longitude = e.latLng.getLng(); // 经度
                this.form.latitude = e.latLng.getLat(); // 纬度
                setMarker();
                this.getAddressFormat();
            });
        },

        searchAddress(keyword = '') {
            if (!keyword) return;

            this.markerLayer.setGeometries([]); // 清空当前标注层

            this.searchEr
                .searchRectangle({
                    keyword,
                    bounds: this.map.getBounds(),
                })
                .then((result) => {
                    // 确保结果数组不为空
                    console.log(result, 333);

                    if (result.data && result.data.length > 0) {
                        const firstItem = result.data[0];
                        const location = firstItem.location || { lat: 28.616202, lng: 115.942693 };
                        const { lat = 28.616202, lng = 115.942693 } = location; // 提供默认值以防location为空

                        // 设置地图中心到第一个搜索结果的位置
                        this.map.setCenter(new window.TMap.LatLng(lat, lng));

                        // 更新标注层，只添加第一个搜索结果
                        let geometries = this.markerLayer.getGeometries();
                        geometries.push({
                            id: '0', // 使用固定ID或任何您希望的ID生成逻辑
                            position: location,
                        });
                        this.markerLayer.updateGeometries(geometries);
                    }
                })
                .catch((error) => {
                    console.error('搜索地址时出错:', error);
                });
        },
        // 获取具体地址
        getAddressFormat() {
            const { longitude, latitude } = this.form;
            this.geocoder
                .getAddress({
                    location: new window.TMap.LatLng(latitude, longitude),
                })
                .then((res) => {
                    console.log(res, 444);

                    const {
                        formatted_addresses: { recommend = '' },
                    } = res.result || {};
                    // console.log(recommend, 'recommend');
                    this.form.hotelDetailAddress = recommend;
                    console.log(recommend, 999);

                    // console.log(this.form);
                    this.$emit("getAddress", {
                        // 地址
                        address: recommend,
                        // 经度
                        latitude: latitude,
                        // 纬度
                        longitude: longitude
                    })
                });
        },
    },
}
</script>
//样式
<style>
.map-box {
    position: relative;

    .map-search {
        z-index: 1000;
        display: flex;
        position: absolute;
        top: 20px;
        left: 20px;
        width: 350px;

        button {
            border-radius: 0;
        }
    }
}

.icons {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.time {
    margin-top: 15px;
    width: 100%;
    font-size: 12px;
    flex-wrap: wrap;
    height: 70%;
}
</style>